package com.reborn.first.initiator;

import lombok.extern.slf4j.Slf4j;
import quickfix.Application;
import quickfix.FieldNotFound;
import quickfix.IncorrectTagValue;
import quickfix.Message;
import quickfix.MessageCracker;
import quickfix.Session;
import quickfix.SessionID;
import quickfix.UnsupportedMessageType;
import zb.fix.entity.message.MsgTypeZb;
import zb.fix.entity.message.ZbError;
import zb.fix.kits.BufferKit;

/**
 * Created by xuqian_sx on 2017-7-27.
 */
@Slf4j
public class MyInitiatorApplication extends MessageCracker implements Application {
	@Override
	public void onCreate(SessionID sessionID) {
		System.out.println("登陆 initiator:session created!");
	}

	@Override
	public void onLogon(SessionID sessionID) {
		System.out.println("客户端登陆成功时候调用此方法 initiator:logon");
	}

	@Override
	public void onLogout(SessionID sessionID) {
		System.out.println("登出 initiator:on logout");
	}

	@Override
	public void toAdmin(quickfix.Message message, SessionID sessionID) {
		System.out.println("发送会话消息时候调用此方法 initiator:to admin--->" + message);
	}

	@Override
	public void fromAdmin(quickfix.Message message, SessionID sessionID) throws FieldNotFound {
		this.myReceive(message, sessionID);
	}

	@Override
	public void toApp(quickfix.Message message, SessionID sessionID) {
		System.out.println("发送业务消息时候调用此方法initiator:to App");
	}

	@Override
	public void fromApp(quickfix.Message message, SessionID sessionID) throws FieldNotFound {
		this.myReceive(message, sessionID);
	}

	@Override
	protected void onMessage(Message message, SessionID sessionID)
			throws FieldNotFound, UnsupportedMessageType, IncorrectTagValue {
		this.myReceive(message, sessionID);
	}

	private void myReceive(Message message, SessionID sessionID) {
		BufferKit sb = new BufferKit();
		sb.appendln("------------------接收start");
		try {
			String msgType = message.getHeader().getString(35);
			sb.appendln("订阅类型" + msgType);
			Session session = Session.lookupSession(sessionID);
			switch (msgType) {
			case MsgTypeZb.LOGON: {
				session.logon();
				session.sentLogon();
				sb.appendln("接收并登陆");
				break;
			}
			case MsgTypeZb.HEARTBEAT: {
				sb.appendln("收到心跳:" + message.toString());
				break;
			}
			case MsgTypeZb.zbError: {
				sb.appendln("收到zb异常:" + message.toString());
				ZbError a = (ZbError) message;
				System.out.println("编码:"+a.getCode()+"内容:"+a.getMsgEn());
				
			}
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		sb.appendln("------------------接收end");
		System.out.println(sb.toString());
	}

}
